package com.qf.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.common.createcode.ODDGenerator;
import com.qf.common.orderstate.OrderState;
import com.qf.entity.dto.Orders;
import com.qf.entity.po.LoginMerchant;
import com.qf.mapper.OrdersMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrdersService extends ServiceImpl<OrdersMapper, Orders> {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Transactional(readOnly = true)
    public int getBuyerNumberByGoodsId(Long goodsId) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Orders::getGoodsId, goodsId)
                .eq(Orders::getPayStatus,OrderState.ALREADY_PAID.getCode());
        return this.count(wrapper);
    }

    @Transactional
    public void createOrder(Orders orders, LoginMerchant loginMerchant) {
        final String prefix = ODDGenerator.getD(StringUtils.replace(UUID.randomUUID().toString(), "-", ""));
        final String suffix = StringUtils.replace(sdf.format(new Date()), "-", "");
        //填充订单编号
        orders.setNumber(prefix + suffix);
        orders.setMerchantId(loginMerchant.getId());
        orders.setPayStatus(OrderState.WAIT_PAID.getCode());
        this.save(orders);
    }

    @Transactional(readOnly = true)
    public List<Orders> getOrderListByMerchantId(Long merchantId) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Orders::getMerchantId,merchantId)
                .orderByDesc(Orders::getCreateTime);
        return this.list(wrapper);
    }

    @Transactional
    public boolean updatePayState(String number, Long code) {
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .eq(Orders::getNumber,number)
                .set(Orders::getPayStatus,code);
        this.update(updateWrapper);
        return true;
    }
}
